package com.max.eshop.parsers;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.max.eshop.core.Book;

public class ParserBooks {
	private final static String space = " ";
	private ArrayList<Book> books = new ArrayList<Book>();
	private String[] booksFile;

	public ArrayList<Book> returnBooks(String[] booksFile) {
		for (int i = 0; i < booksFile.length - 1; i++) {
			if (!booksFile[i + 1].equals(null)) {
				String temp[] = booksFile[i + 1].split(" ");
				Date dateOfPublication = null;
				Date dateOfReceipt = null;
				try {
					dateOfPublication = new SimpleDateFormat("dd.MM.yyyy")
							.parse(temp[1]);
					dateOfReceipt = new SimpleDateFormat("dd.MM.yyyy")
							.parse(temp[3]);

				} catch (ParseException e) {
					e.printStackTrace();
				}
				try {
					books.add(new Book(temp[0].toString(), dateOfPublication,
							temp[2].toString(), dateOfReceipt, Integer
									.parseInt(temp[4]), Integer
									.parseInt(temp[5])));
				} catch (NullPointerException e) {
					System.out.println("ERROR");
				}
			}
		}
		return books;
	}

	public String[] booksToSrting(List<Book> books2) {
		booksFile = new String[books2.size() + 1];
		booksFile[0] = "name dateOfPublication description dateOfRrceipt count price";
		DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
		for (int i = 0; i <= books2.size() - 1; i++) {

			booksFile[i + 1] = books2.get(i).getName() + space
					+ dateFormat.format(books2.get(i).getDateOfPublication())
					+ space + books2.get(i).getDescription() + space
					+ dateFormat.format(books2.get(i).getDateOfReceipt())
					+ space + books2.get(i).getCount() + space
					+ books2.get(i).getPrice();
		}
		return booksFile;
	}
}